// pages/cart/index.js
import { chooseAddress, showModal,showToast } from '../../utils/getAddress'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userAddress: {},
    goods: [],
    price: 0,
    totalSelect: null,
    payNumber: 0
  },
  onShow () {
    //初始化地址
    this._getgoodsInfo()
    //初始化商品数据
    const goods = wx.getStorageSync('goods')||[]
    this.setData({
      goods
    })
    //初始化底部数据
    this._computedPrice(goods)
  }
  ,
  async addAdressInfo () {
    const address = wx.getStorageSync('address');
    if (!address) {
      const res = await chooseAddress()
      wx.setStorageSync('address', res);
      this.setData({
        userAddress: res
      })
    } else {
      this.setData({
        userAddress: address
      })
    }
  },
  //初始化地址，进入页面就加载
  _getgoodsInfo () {
    const address = wx.getStorageSync('address');
    if (address) {
      this.setData({
        userAddress: address
      })
    }
  },
  //点击商品选择按钮
  handelChecked (e) {
    const cart = this.data.goods
    const { id } = e.target.dataset
    const index = cart.findIndex((item) => {
      return item.goods_id == id
    })
    cart[index].check = !cart[index].check
    this._computedPrice(cart)
  },
  //点击底部全选按钮，功能
  allSelectCheck () {
    const cart = this.data.goods
    const checked = !this.data.totalSelect
    cart.forEach(item => {
      item.check = checked
    })
    this._computedPrice(cart)
  },
  async handelNum (e) {
    const { id, operate } = e.target.dataset
    const cart = this.data.goods
    const index = cart.findIndex((item) => {
      return item.goods_id == id
    })
    if ((cart[index].num == 1) && (operate == -1)) {
      const res = await showModal({ content: '你确认删除此商品嘛？' })
      if(res){
        cart.splice(index,1)
      }
    } else {
      cart[index].num = cart[index].num + operate
    }
    this._computedPrice(cart)
  },
  //底部计算
  _computedPrice (cart) {
    let totalSelect = true;
    let price = 0
    let payNumber = 0
    cart.forEach(item => {
      if (item.check) {
        price += item.num * item.goods_price
        payNumber += item.num
      } else {
        totalSelect = false
      }
    })
    this.setData({
      totalSelect,
      price,
      payNumber,
      goods: cart
    })
    wx.setStorageSync("goods", cart);
  },
  async navigatorPay(){
    if(!this.data.userAddress.userName){
      return await showToast({title:"你还没添加地址！"})
    }
    if(this.data.goods.length<=0||this.data.price ==0){
      return await showToast({title:"你还没添加商品呢！"})
    }
    wx.navigateTo({
      url: '../pay/index'
    });
  }
})